package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.conf.LoadCloumnsConfig;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Discription:  查询系统云仓订单,以消息队列发送
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/10/23 12:39
 */
@Slf4j
@Component
public class PushOrderService {

    @Autowired
    private SendMqServies sendMq;
    @Autowired
    private ChangeCloudStatusService changeCloudStatusService;
    @Autowired
    private LoadCloumnsConfig loadCloumnsConfig;
    @Autowired
    private PropertiesConf pconf;
    @Autowired
    private LocalLogService localLogService;
    /**
     * 库存启动
     */
    public void pushStart() {
        // 获取自身 bean
        PushOrderService pushOrderService = ApplicationContextHandle.getBean(PushOrderService.class);
        pushOrderService.pushOrder();
    }
    /**
     * 循环遍历查询库存异动表,发出待更新库存
     *
     * @throws Exception
     */
    @Transactional
    public void pushOrder() {

        try {
            // 需要查询的字段
            String files = pconf.getProperty("ons.pushorderFiles");
            int rownums = pconf.getPropertyInt("ons.pushorderNum");
            // 查询同步库存表中等待同步的总数
            String countSql = "select * from YSN_NOTICESITEM where EDIFLAG = 80 and  rownum <= " + rownums + " order by " +
                    "id for update skip locked";
            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);
            // 有需要同步的云仓订单 将查询到的数据以消息形式发送
            if (jsonArr == null || jsonArr.isEmpty()) {
                log.debug("cloud Order jsonArr is null");
                return;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",jsonArr.toJSONString());
            sendMq.sendMqinfoObj(jsonObject, pconf.getProperty("ons.pushorderTopic", "DATAV_CLOUD_ORDER"), pconf.getProperty("ons.pushorderTag", "erro"));
            // 更改云仓订单同步状态
            changeCloudStatusService.changeStatusSuc(jsonArr);

        } catch (Exception e) {
            //  同步云仓订单出现异常,修改云仓订单状态为 90
            log.error("同步云仓订单失败");
        }
    }
}
